const Router = require('koa-router');
const router = new Router();
const {db,Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
// 获取页面设置
router.post('/subject/save', async ctx => {
    let user = ctx.user
    let tenantId = ctx.user.tenantId;
    let formData = ctx.request.body.formData;
    let name = formData.name?tool.xe.trim(formData.name):''
    let id = formData.id
    let pid = formData.pid
    let remark = formData.remark?formData.remark:''
    if(!name) return ctx.err('请输入名称')
    if(id) {
        let has = await db.query(`select count(*) total from category where tenantId=${tenantId} and typeNumber='subject' and name='${name}' and id<>${id} `,{type: QueryTypes.SELECT,plain: true})
        if(has.total > 0) return ctx.err(`${name} 科目名称已存，不能重复`)
        let model = await db.models['category'].findOne({
            where: {
                tenantId,
                id
            }
        })
        if(model.isInit === 1) return ctx.err('不能修改系统科目')
        model.name = name
        model.state = '启用'
        model.isInit = 0
        model.pinYin = tool.py(name)
        model.remark = remark
        await model.save()
    }
    else {
        // 新增
        let has = await db.query(`select count(*) total from category where tenantId=${tenantId} and typeNumber='subject' and name='${name}' `,{type: QueryTypes.SELECT,plain: true})
        if(has.total > 0) return ctx.err(`${name} 科目名称已存，不能重复`)
        let model = db.models['category'].build()
        let pidModel = await db.models['category'].findOne({
            where: {
                id: pid
            }
        })
        let fl = pidModel.code.substring(0,1)
        if(fl === '1') { fl = '资产'}
        if(fl === '2') { fl = '负债'}
        if(fl === '4') { fl = '权益'}
        if(fl === '5') { fl = '损益'}
        model.tenantId = tenantId
        model.typeNumber = 'subject'
        model.name = name
        model.fl = fl
        model.pinYin = tool.py(name)
        model.state='启用'
        model.isInit = 0
        model.remark = remark
        model.ctime = tool.getTime()
        model.disabled = 0
        if(pid) {
            let code = await setCode(tenantId,'category', pid)
            model.code = tool.xe.toString(code)
            let pidModel = await db.query(`select id,direct from category where tenantId=${tenantId} and id=${pid} `,{type: QueryTypes.SELECT, plain: true})
            model.direct = pidModel.direct
            model.pid = pid
        }
        else {
            if(fl === '资产') {
                code = '1'
            }
            if(fl === '负债') {
                code = '2'
            }
            if(fl === '权益') {
                code = '4'
            }
            if(fl === '损益') {
                code = '6'
            }
            let pidModel = await db.query(`select id,direct from category where tenantId=${tenantId} and code=${code} `,{type: QueryTypes.SELECT, plain: true})
            if(pidModel) {
                let code = await setCode(tenantId,'category', pidModel.id)
                model.code = tool.xe.toString(code)
                model.direct = pidModel.direct
                model.pid = pidModel.id
            }
            else {
                let code = await setCode(tenantId,'category', 0)
                model.code = tool.xe.toString(code)
                model.direct = ''
                model.pid = 0
            }
        }
        model.cby = user.id
        await model.save()
        return ctx.suc('已新增')
    }
})
// 自动设置编码
const setCode = async (tenantId,tableName,pid) => {
    if(pid !== 0) {
        let pidModel = await db.query(`select * from ${tableName} where tenantId=${tenantId} and id=${pid} `,{type: QueryTypes.SELECT, plain: true})
        if(!pidModel) {
            throw new Error('未找到数据')
        }
        let last = await db.query(`select top 1 * from ${tableName} where tenantId=${tenantId} and pid =${pid} order by code desc `,{type: QueryTypes.SELECT, plain: true})
        if(last) {
            let code = tool.xe.add(last.code, 1)
            return code
        }
        else {
            let code = pidModel.code + '01'
            return code
        }
    }
    else {
        let last = await db.query(`select top 1 * from ${tableName} where tenantId=${tenantId} and isnull(pid,0)=0 order by code desc `,{type: QueryTypes.SELECT, plain: true})
        if(last) {
            let code = tool.xe.add(last.code, 1)
            return code
        }
        else {
            let code = '10'
            return code
        }
    }
    return ''
}


module.exports = router;